<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.value" clearable placeholder="输入搜索内容" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
          <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" style="width:350px" />
            </el-form-item>
            <el-form-item label="是否生效"  prop="status" required>
              <el-radio-group v-model="form.status">
              <el-radio label="0">是</el-radio>
              <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="saveTemplate">确认</el-button>
        </div>
      </el-dialog>
      <relatedBrand ref="form1" />
      <relatedAttribute ref="form2" />
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column v-if="columns.visible('id')" prop="id" label="模板Id" />
        <el-table-column v-if="columns.visible('categoryId')" prop="categoryId" label="分类Id"/>
        <el-table-column v-if="columns.visible('templateName')" prop="templateName" label="模板名称" />
        <el-table-column  label="品牌" >
          <template slot-scope="scope">
            <el-button type="warning" size="mini" icon="el-icon-edit" @click="relatedBrand(scope.row)">关联品牌</el-button>
          </template>
        </el-table-column>
        <el-table-column  label="属性">
          <template slot-scope="scope">
            <el-button type="success" size="mini" icon="el-icon-edit" @click="relatedAttribute(scope.row)">关联属性</el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('status')" prop="status" label="是否有效">
          <template slot-scope="scope">
            <span v-if="scope.row.status =='0'">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column  label="操作" width="130px" align="center" fixed="right">
             <template slot-scope="scope">
              <el-popover :ref="scope.row.id" placement="top" width="180">
                <p>确定删除本条数据吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button
                    size="mini"
                    type="text"
                    @click="$refs[scope.row.id].doClose()"
                  >取消</el-button>
                  <el-button
                    :loading="delLoading"
                    type="primary"
                    size="mini"
                    @click="subDelete(scope.row.id)"
                  >确定</el-button>
                </div>
                <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </el-popover>
            </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import storeTemplate,{getAllBrand,del,add} from '@/api/storeTemplate'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import relatedBrand from "./relatedBrand";
import relatedAttribute from "./relatedAttribute";

// crud交由presenter持有
const defaultCrud = CRUD({ title: '模板', url: 'api/getTemplateList',   optShow: { add: true, edit: false, del: false, download: true}})
const defaultForm = { id: null, uid: null, orderId: null, price: null, rechargeType: null, paid: null, payTime: null, addTime: null, refundPrice: null, nickname: null }
export default {
  name: 'storeTemplate',
  components: { pagination, crudOperation, rrOperation, udOperation,relatedBrand,relatedAttribute },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      permission: {
        add: ['admin', 'UserRecharge:add'],
        edit: ['admin', 'UserRecharge:edit'],
        del: ['admin', 'UserRecharge:del']
      },
      form:{
        id:'',
        templateName:'',
        status:0,
      },
      rules: {
        templateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ]
      },
      delLoading: false,
      queryTypeOptions: [
        { key: 'templateName', display_name: '模板名称' }
      ]
    }
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      const query = this.query
      if (query.type && query.value) {
        this.crud.params[query.type] = query.value
      }
      return true
    },
    relatedBrand(data){
      const brandArray=JSON.parse(data.brands)
      const ids=[]
      for(let i=0;i<brandArray.length;i++){
        ids.push(brandArray[i].id)
      }
      const _this = this.$refs.form1;
      _this.form = {
        id: data.id,
        ids:ids
      };
      console.log(ids,"ids")
      getAllBrand().then((res)=>{
         _this.data=res.data
      })
      _this.dialog = true;
    },
    relatedAttribute(data){
      const attributeArr=JSON.parse(data.attribute)
      console.log(JSON.parse(data.attribute),"attribute")
      const _this = this.$refs.form2;
      _this.form = {
        id: data.id,
        attribute:attributeArr
      };
      _this.dialog = true;
    },
    saveTemplate() {
      this.loading = true;
      console.log(this.form,"======")
      add(this.form)
        .then((res) => {
          //this.resetForm();
          this.$notify({
            title: "添加成功",
            type: "success",
            duration: 2500,
          });
          this.loading = false;
          this.crud.toQuery();
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },
    subDelete(id){
       this.delLoading = true;
      del(id)
        .then((res) => {
          this.delLoading = false;
          this.$refs[id].doClose();
          this.crud.toQuery();
          this.$notify({
            title: "删除成功",
            type: "success",
            duration: 2500,
          });
        })
        .catch((err) => {
          this.delLoading = false;
          this.$refs[id].doClose();
          console.log(err.response.data.message);
        });
    }
  },
  resetForm(){
    this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
        id:'',
        templateName:'',
        status:0
      }
    }
}
</script>

<style scoped>

</style>
